﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace LikeTryCore
{
    public enum ReturnType
    {
        String = 1,
        File = 2
    }

    public class WebHelper
    {
        public CookieContainer Cookie;
        public static string Logon = "http://www.liketry.com/user_login.php ";

        public WebHelper()
        {
            Cookie = new CookieContainer();
        }

        //returnurl=http%3A%2F%2Fliketry.com%2F&username=UserName&password=PWD&yzm=4413&op=login
        public string DoPost(string url, string data, bool useProxy = false, IWebProxy proxy = null, bool loopToFindResult = false, string referer = null)
        {
            int times = 0;
            do
            {
                try
                {
                    var request = this.GetRequest(url, "post", data, useProxy, proxy,referer);
                    var content = this.GetResponse(request, ReturnType.String);
                    return content;
                }
                catch
                {
                    if (loopToFindResult)
                    {
                        times++;
                        if (times > 10)
                        {
                            throw;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            while (true);

        }

        public string DoGet(string url, ReturnType type = ReturnType.String, bool useProxy = false,IWebProxy proxy = null,bool loopToFindResult = false)
        {
            int times = 0;
            do
            {
                try
                {
                    var request = this.GetRequest(url, useProxy: useProxy, proxy: proxy);
                    return this.GetResponse(request, type);
                }
                catch
                {
                    if (loopToFindResult)
                    {
                        times++;
                        Thread.Sleep(2000);
                        if (times > 10)
                        {
                            throw;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            while (true);

        }

        private string GetResponse(HttpWebRequest request, ReturnType returnType)
        {
            var result = string.Empty;
            try
            {
                var response = (HttpWebResponse)request.GetResponse() as HttpWebResponse;

                string content = string.Empty;
                List<byte> lists = new List<byte>();
                using (var stream = response.GetResponseStream())
                {
                    MemoryStream memory = new MemoryStream();
                    int data = -1;
                    do
                    {
                        data = stream.ReadByte();
                        if (data != -1)
                        {
                            lists.Add((byte)data);
                        }

                    } while (data != -1);

                    if (returnType == ReturnType.String)
                    {
                        result = ASCIIEncoding.UTF8.GetString(lists.ToArray());
                    }
                    else
                    {
                        File.WriteAllBytes(System.IO.Path.Combine(Environment.CurrentDirectory, result), lists.ToArray());
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine( exp.Message);
            }
                 

            return result;
        }

        private HttpWebRequest GetRequest(string url, string method = "get", string data ="",bool useProxy = false, IWebProxy proxy = null, string referer = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = Cookie;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1";
            if (string.IsNullOrEmpty(referer))
            {
                request.Referer = "http://liketry.com/user_login.php";
            }
            else
            {
                request.Referer = referer;
            }

            //request.Headers.Add("Host", "liketry.com");
            request.ProtocolVersion = new Version(1, 0);
            if (useProxy)
            {
                request.Proxy = proxy;
            }

            if (method.ToUpperInvariant().Equals("POST"))
            {
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                using (var stream = request.GetRequestStream())
                {
                    var bytes = ASCIIEncoding.ASCII.GetBytes(data);
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                }
            }

            return request;
        }
    }
}
